<?php


namespace Modules\Chinadmin\Services;


use Illuminate\Support\Facades\DB;
use Modules\Chinadmin\Http\Controllers\Dispatch\Message;
use Modules\Chinadmin\Models\MessageModel;
use Modules\Chinadmin\Models\MessageReadModel;

/**
 * 消息通知逻辑处理
 * Class MessageServices
 * @package Modules\Chinadmin\Services
 */
class MessageServices
{


    /**
     * 列表
     * @param $store_user
     * @param $type
     * @return \Illuminate\Contracts\Pagination\Paginator
     */
    public function getList($store_user, $type)
    {
        $query = DB::table('ca_message')
            ->select('ca_message.*', 'ca_message_read.is_read')
            ->leftJoin('ca_message_read', function ($join) use($store_user) {
                $join->on('ca_message.message_id', '=', 'ca_message_read.message_id')
                ->where('ca_message_read.account_id', $store_user['id']);
            })
            ->where('type', $type);
        if($type !== 1) {
            $query->where('company_id', $store_user->company_id);
        }
        $list = $query->simplePaginate(10);
        return $list;
    }


    /**
     * 消息已读
     * @param $store_user
     * @param int $message_id
     * @return bool
     */
    public function read($store_user, $message_id = 0)
    {
        // 单个消息已读
        if($message_id) {
            $readLog = MessageReadModel::where(['message_id' => $message_id, 'account_id' => $store_user['id']])->first();
            if($readLog) {
                return false;
            }
            $model = new MessageReadModel;
            $model->message_id = $message_id;
            $model->account_id = $store_user['id'];
            $model->is_read = 1;
            $result = $model->save();
        }else {
            // 查询当前所有记录
            $messageList = DB::table('ca_message')
                ->select('ca_message.message_id', 'ca_message_read.is_read')
                ->leftJoin('ca_message_read', function ($join) use($store_user) {
                    $join->on('ca_message.message_id', '=', 'ca_message_read.message_id')
                        ->where('ca_message_read.account_id', $store_user['id']);
                })
                ->whereRaw("if (`type` <> 1, `company_id` = {$store_user['company_id']}, `status` = 'on' )")
                ->get();
            if($messageList) {
                $insertData = [];
                foreach ($messageList as $message) {
                    if($message->is_read == 1) {
                        continue;
                    }
                    $insertData[] = [
                        'message_id' => $message->message_id,
                        'is_read' => 1,
                        'account_id' => $store_user['id']
                    ];
                }
                $insertData && MessageReadModel::upsert($insertData, ['message_id', 'account_id']);
            }
            $result = true;
        }
        return $result;
    }

}
